package hw1;

import java.io.StringWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.googlecode.jatl.Html;
import com.mysql.jdbc.ResultSetMetaData;
import java.sql.Statement;

public class Questions {

    private final List<Question> questions = new ArrayList<Question>();
    private String result;
    
    public void add(Question question) {
        questions.add(question);
    }
    
    // not the most generic method, oh well.
    @SuppressWarnings("unused")
    public void excecute(final Statement st) throws SQLException {

        final StringWriter writer = new StringWriter();
        Html html = new Html(writer) {{
            html();
                head();
                    link().rel("stylesheet").type("text/css").href("style.css").end();
                end(); //head
                body();
                
                h1().text("Homework Assignment #1 - Database Systems").end();
                
                for (Question q : questions) {
                    ResultSet rs = st.executeQuery(q.getQuery());
                    ResultSetMetaData rsmd = (com.mysql.jdbc.ResultSetMetaData)rs.getMetaData();
                
                    h3().text("Q" + q.getQuestionNumber()).end();
                    p().raw(q.getAssumption().replaceAll("\\n", "<br />")).end();
                    pre().raw(q.getQuery().replaceAll("\\n", "</br>")).end();
                    br();
                    table().border("1");
                        thead().tr();
                        for (int i=1; i<=rsmd.getColumnCount(); i++) {
                            th().text(rsmd.getColumnName(i)).end();
                        } 
                        end().end(); // tr, thead
                        tbody();
                        int lineCounter = 0;
                        while (rs.next()) {
                            lineCounter += 1;
                            tr();
                            for (int i=1; i<=rsmd.getColumnCount(); i++) {
                                Object o = rs.getObject(i);
                                td().text(o == null ? "null" : o.toString()).end();
                            }
                            end(); // tr
                            
                            if (q.getQuestionNumber() == 8 && lineCounter == 10) {
                                break;
                            }
                        }
                        end(); // tbody
                    end(); // table
                }
                end(); // body
            end(); // html
            done();
        }};

        result = writer.toString();
    }
    
    @Override
    public String toString() {
        return result;
    }
    
}
